#!/bin/bash

if [ -z "$1" ] || [ "$1" == "--help" ]; then
  echo "Using $0 [BSSID] [OPTIONS]";
  echo "[OPTIONS] are:";
  echo "  --group-by-day - Grouping PIN dates, by day and shows PIN count of each day";
  echo "  --group-by-hour - Grouping PIN hours, by day+hour and shows PIN count of each day+hour";
  exit;
fi
source $(pwd)"/configurationSettings";
if [[ ! -d "$PIN_DATE_TMP_DIR" ]]; then
  echo "Your PIN_DATE_TMP_DIR doesn't exist";
  echo "See ./configurationSettings file";
  exit;
fi
F=$PIN_DATE_TMP_DIR"/"$(echo "$1" | sed s/://g);
if [[ ! -f "$F" ]]; then
   echo "File $F doesn't exist";
   exit;
fi

# ${@:2} - means arguments array from $2 element
if [[ ${@:2} =~ "--group-by-day" ]]; then
  echo "Grouping PINs by day";
  cat $F | gawk 'BEGIN { curDate=""; cnt=0; } 
		  { 
		        if (curDate=="") { curDate=strftime("%Y-%m-%d", $0); }
			if (curDate==strftime("%Y-%m-%d",$0)){ cnt++; next; } 
			else { print curDate ": " cnt " PINs"; cnt=1; curDate=strftime("%Y-%m-%d", $0); }
		  }
		  END {
			print curDate ": " cnt " PINs"; 
		  }';
elif [[ ${@:2} =~ "--group-by-hour" ]]; then
  echo "Grouping PINs by hour";
  cat $F | gawk 'BEGIN { curDate=""; cnt=0; } 
		  { 
		        if (curDate=="") { curDate=strftime("%Y-%m-%d %H", $0); }
			if (curDate==strftime("%Y-%m-%d %H",$0)){ cnt++; next; } 
			else { print curDate ":00 : " cnt " PINs"; cnt=1; curDate=strftime("%Y-%m-%d %H", $0); }
		  }
		  END {
			print curDate ":00 : " cnt " PINs"; 
		  }';
else
  cat $F | gawk '{ print strftime("%Y-%m-%d %H:%M:%S",$0); }';
fi

